package ai.mspbots.poc.help;

import org.languagetool.JLanguageTool;
import org.languagetool.language.BritishEnglish;
import org.languagetool.rules.Rule;
import org.languagetool.rules.RuleMatch;

import java.util.List;

public class SpellCheckHelper {

    public static JLanguageTool langTool = new JLanguageTool(new BritishEnglish());

    static {
        for (Rule rule : langTool.getAllActiveRules()) {
            if (!rule.isDictionaryBasedSpellingRule()) {
                langTool.disableRule(rule.getId());
            }
        }
    }
    public static String correctGrammar(String text) {
        String result = text;
        try {
            List<RuleMatch> matches = langTool.check(text);

            // 如果有错误，进行简单的替换
            for (RuleMatch match : matches) {
                String suggestedCorrection = match.getSuggestedReplacements().isEmpty() ? text : match.getSuggestedReplacements().get(0);
                System.out.println("suggestedCorrection = " + suggestedCorrection);
                // result = text.replace(match.getMessage(), suggestedCorrection);

                // 使用 fromPos 和 toPos 进行替换
                result = new StringBuilder(text)
                        .replace(match.getFromPos(), match.getToPos(), suggestedCorrection)
                        .toString();
            }
        } catch (Exception e) {
            return text;
        }
        if (result != null) {
            return result;
        }
        return text;
    }
}
